// pages/upload/upload.js - 严格按照test示例设计规范
Page({
  data: {
    contentType: 'post',
    content: '',
    mediaList: [],
    topicInput: '',
    topics: [],
    location: '',
    privacyType: 'public',
    canPublish: false
  },

  onLoad() {
    console.log('上传页面加载完成');
    this.checkCanPublish();
  },

  // 选择内容类型
  selectType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      contentType: type
    });
    this.checkCanPublish();
  },

  // 内容输入
  onContentInput(e) {
    this.setData({
      content: e.detail.value
    });
    this.checkCanPublish();
  },

  // 话题输入
  onTopicInput(e) {
    this.setData({
      topicInput: e.detail.value
    });
  },

  // 添加话题
  addTopic() {
    const topic = this.data.topicInput.trim();
    if (!topic) {
      wx.showToast({
        title: '请输入话题',
        icon: 'none'
      });
      return;
    }

    if (this.data.topics.includes(topic)) {
      wx.showToast({
        title: '话题已存在',
        icon: 'none'
      });
      return;
    }

    this.setData({
      topics: [...this.data.topics, topic],
      topicInput: ''
    });
  },

  // 移除话题
  removeTopic(e) {
    const index = e.currentTarget.dataset.index;
    const topics = this.data.topics.filter((_, i) => i !== index);
    this.setData({
      topics: topics
    });
  },

  // 添加媒体
  addMedia() {
    const that = this;
    wx.chooseMedia({
      count: 9 - this.data.mediaList.length,
      mediaType: ['image', 'video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        const mediaList = res.tempFiles.map(file => ({
          type: file.fileType === 'image' ? 'image' : 'video',
          url: file.tempFilePath,
          size: file.size
        }));
        
        that.setData({
          mediaList: [...that.data.mediaList, ...mediaList]
        });
        that.checkCanPublish();
      },
      fail(err) {
        console.error('选择媒体失败', err);
        wx.showToast({
          title: '选择失败',
          icon: 'none'
        });
      }
    });
  },

  // 删除媒体
  deleteMedia(e) {
    const index = e.currentTarget.dataset.index;
    const mediaList = this.data.mediaList.filter((_, i) => i !== index);
    this.setData({
      mediaList: mediaList
    });
    this.checkCanPublish();
  },

  // 选择位置
  selectLocation() {
    wx.chooseLocation({
      success: (res) => {
        this.setData({
          location: res.name
        });
      },
      fail: (err) => {
        console.error('选择位置失败', err);
        wx.showToast({
          title: '选择位置失败',
          icon: 'none'
        });
      }
    });
  },

  // 切换隐私设置
  togglePrivacy(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      privacyType: type
    });
  },

  // 检查是否可以发布
  checkCanPublish() {
    const canPublish = this.data.content.trim().length > 0 || this.data.mediaList.length > 0;
    this.setData({
      canPublish: canPublish
    });
  },

  // 发布内容
  publishContent() {
    if (!this.data.canPublish) {
      wx.showToast({
        title: '请输入内容或添加媒体',
        icon: 'none'
      });
      return;
    }

    // 显示加载中
    wx.showLoading({
      title: '发布中...'
    });

    // 上传媒体文件
    this.uploadMedia().then(() => {
      // 发布内容
      this.publishToServer();
    }).catch(err => {
      console.error('发布失败', err);
      wx.hideLoading();
      wx.showToast({
        title: '发布失败',
        icon: 'none'
      });
    });
  },

  // 上传媒体文件
  uploadMedia() {
    if (this.data.mediaList.length === 0) {
      return Promise.resolve();
    }

    const uploadPromises = this.data.mediaList.map(media => {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: 'https://api.example.com/upload',
          filePath: media.url,
          name: 'file',
          formData: {
            type: media.type
          },
          success: (res) => {
            const data = JSON.parse(res.data);
            resolve({
              type: media.type,
              url: data.url,
              size: media.size
            });
          },
          fail: reject
        });
      });
    });

    return Promise.all(uploadPromises).then(uploadedMedia => {
      this.setData({
        uploadedMedia: uploadedMedia
      });
    });
  },

  // 发布到服务器
  publishToServer() {
    const publishData = {
      type: this.data.contentType,
      content: this.data.content,
      media: this.data.uploadedMedia || [],
      topics: this.data.topics,
      location: this.data.location,
      privacy: this.data.privacyType,
      timestamp: Date.now()
    };

    // 模拟发布请求
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '发布成功',
        icon: 'success'
      });
      
      // 清空表单
      this.resetForm();
      
      // 返回上一页或跳转到社区
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }, 2000);
  },

  // 重置表单
  resetForm() {
    this.setData({
      contentType: 'post',
      content: '',
      mediaList: [],
      topicInput: '',
      topics: [],
      location: '',
      privacyType: 'public',
      canPublish: false,
      uploadedMedia: []
    });
  },

  // 页面返回确认
  onUnload() {
    if (this.data.content.trim() || this.data.mediaList.length > 0) {
      wx.showModal({
        title: '确认离开',
        content: '当前有未保存的内容，确定要离开吗？',
        success: (res) => {
          if (res.confirm) {
            // 用户确认离开
          } else {
            // 用户取消，阻止返回
            return false;
          }
        }
      });
    }
  }
});